#pragma once

#include<iostream>
#include<string>
#include<sstream>
#include<unistd.h>
#include<string>
#include<vector>
#include<unordered_map>
#include<sys/types.h>
#include<sys/socket.h>
#include"Util.hpp"
#include"log.hpp"

#define SEP ": " //分隔符利用宏定义

class HttpRequest
{
public:
    std::string request_line;//请求行
    std::vector<std::string> request_header;
    std::string blank;
    std::string request_body;

    //解析后的结果(方法、URL、版本)
    std::string method;
    std::string url;
    std::string version;

    //解析后结果放入kv中
    std::unordered_map<std::string , std::string> header_kv;
    int content_length;
public:
    HttpRequest():content_length(0){}
    ~HttpRequest(){}
};

class HttpResponse
{
public:
    std::string status_line;
    std::vector<std::string>response_header;
    std::string blank;
    std::string response_body;
};

//读取请求、分析请求、构建响应、IO通信
class EndPoint
{
private:
    int sock;
    HttpRequest http_request;
    HttpResponse http_response;
private:
    void RecvHttpRequestLine()
    {
        auto &line = http_request.request_line;
        //读取首行到http_request的首行中去
        Util::ReadLine(sock,line);
        line.resize(line.size()-1);
        LOG(INFO,http_request.request_line);
    }

    void RecvHttpRequestHeader()
    {
        std::string line;
        while(true)
        {
            //每次读取前保证缓冲Line是空的
            line.clear();
            Util::ReadLine(sock,line);
            if(line == "\n") break;
            line.resize(line.size()-1);
            http_request.request_header.push_back(line);
            LOG(INFO,line);
        }
        if(line == "\n")
        {
            http_request.blank = line;
        }
    }

    void ParseHttpRequestLine()
    {
        auto & line = http_request.request_line; 
        std::stringstream ss(line);
        ss>>http_request.method>>http_request.url>>http_request.version;

        LOG(INFO,"--------------验证解析后结果是否正确");
        LOG(INFO,http_request.method);
        LOG(INFO,http_request.url);
        LOG(INFO,http_request.version);
    }

    void  ParseHttpRequestHeader()
    {
        for(auto & iter:http_request.request_header)
        {
            std::string key;
            std::string value;
            if(Util::CutString(iter,key,value,SEP))
            {
                http_request.header_kv.insert({key,value});
            }

            // std::cout<<"debug:"<<key<<std::endl;
            // std::cout<<"debug:"<<value<<std::endl;
        }
    }

    bool  IsNeedRecvHttpRequestBody()
    {
        auto &method = http_request.method;
        if(method == "POST")
        {
            auto &header_kv = http_request.header_kv;
            auto iter = header_kv.find("Content-Length");
            if(iter != header_kv.end())
            {
                //转换成整数存储到content_length中
                http_request.content_length = atoi(iter->second.c_str());
                //确认使用POST方法，并且报文有相应长度的时候，下面便可以开始报文的读取
                return true;
            }
        }
        return false;
    }

    void RecvHttpRequestBody()
    {
        if(IsNeedRecvHttpRequestBody())
        {
            int content_length = http_request.content_length;//读取内容的长度
            auto &body = http_request.request_body;//内容

            char ch =0;
            while (content_length)
            {
                ssize_t s = recv(sock,&ch,1,0);
                if(s>0)
                {
                    body.push_back(ch);
                    content_length--;
                }
                else 
                {
                    break;
                }
            }
            
        }
    }

public:
    EndPoint(int _sock):sock(_sock)
    {}
    //读取请求
    void RcvHttpRequest()
    {
        RecvHttpRequestLine();
        RecvHttpRequestHeader();
    }
    //解析请求 
    void ParseHttpRequest()
    {
        ParseHttpRequestLine();
        //解析报头
        ParseHttpRequestHeader();
        //读取正文
        RecvHttpRequestBody();

    }
    //构建响应
    void BuildHttpResponse()
    {

    }
    //发送相应
    void SendHttpResponse()
    {

    }
    ~EndPoint()
    {
        close(sock);
    }
};

class Entrance
{
    public:
        static void*HandlerRequest(void *_sock)
        {
            LOG(INFO,"Hander Request begin");
            int sock = *(int*)_sock;
            delete(int*)_sock;
            std::cout<<"get a new link :"<<sock<<std::endl;

#ifdef DEBUG
            char buffer[4096];
            recv(sock,buffer,sizeof(buffer),0);
            std::cout<<"________________begin"<<std::endl;
            std::cout<<buffer<<std::endl;
             std::cout<<"________________end"<<std::endl;
#else   
            EndPoint*ep = new EndPoint(sock);
            ep->RcvHttpRequest();
            ep->ParseHttpRequest();
            ep->BuildHttpResponse();
            ep->SendHttpResponse();
            delete ep;
#endif

            // std::string line;
            // Util::ReadLine(sock,line); 
            // std::cout<<line<<std::endl;
            // close(sock);

            LOG(INFO,"Hander Request End");
            return nullptr;
        }
};